package com.vnp.cooking;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.vnp.cooking.adapter.ListCachlamAdapter;
import com.vnp.cooking.bean.ObjCachlam;
import com.vnp.cooking.httpclient.HttpClientHelper;
import com.vnp.cooking.httpclient.MyJsonHttpResponseHandler;
import com.vnp.cooking.utils.KeyboardHelper;
import com.vnp.cooking.utils.PreferenceHelper;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.util.Log;
import android.view.DragEvent;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnDragListener;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class BuocThucHienActivity extends Activity implements OnClickListener, OnItemClickListener{
	
	ImageButton btnBack;
	Button btnSave;
	private GridView gridview;
	View main;
	
	Button btnThembuoc;
	
	ArrayList<ObjCachlam> objCachlams = new ArrayList<ObjCachlam>();
	ListCachlamAdapter adapter;
	ImageButton btnThemanh;
	int last;
	boolean isProccess = false;
	boolean isPosted = false;
	ProgressDialog progressDialog;
	Handler mHandler = new Handler();
	Dialog d, dArlert, dChuapost;
	
	Runnable r = new Runnable() {
		
		@Override
		public void run() {
			saveStepCT();
		}
	};
	
	Runnable rThoat = new Runnable() {
		
		@Override
		public void run() {
			closeActivity();
		}
	};
	
	public static ArrayList<ObjCachlam> objSteps = new ArrayList<ObjCachlam>();
	public static int stepCount =objSteps.size();
	JSONArray step;
	PreferenceHelper preferenceHelper;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_buoc_thuc_hien);
		main = (View) findViewById(R.id.main_grid);
		
		preferenceHelper = new PreferenceHelper(this);
		
		btnBack = (ImageButton) findViewById(R.id.btn_back);
		btnSave = (Button) findViewById(R.id.btn_luu_buoc);
		btnThembuoc = (Button) findViewById(R.id.btn_them);
		gridview = (GridView) findViewById(R.id.grid_buoc_lam);
		last = objCachlams.size()/2;
		fixData();
		init();
		
		gridview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View arg1, int position,
					long id) {
//				 Toast.makeText(BuocThucHienActivity.this, "vitri "+adapter.getPosition(objCachlams.get(position)), Toast.LENGTH_SHORT).show();
            }
			
		});
		
	}
	
	void init() {
		
		adapter = new ListCachlamAdapter(BuocThucHienActivity.this, objSteps);
		gridview.setAdapter(adapter);
		gridview.setOnItemClickListener(this);
		gridview.setSelection(objSteps.size());
		
		gridview.setOnDragListener(new OnDragListener() {
			
			@Override
			public boolean onDrag(View v, DragEvent event) {
				
				return false;
			}
		});
		
		btnBack.setOnClickListener(this);
		btnSave.setOnClickListener(this);
		btnThembuoc.setOnClickListener(this);
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			if (isProccess == true) {
				showDialogProcess();
			} else {
				if(objSteps.size() == 0) {
					closeActivity();
					objSteps.clear();
				} else {
					if (isPosted == true) {
						closeActivity();
					} else {
						showDialogCanhbaochuapost();
					}
					
				}
				
				
				
			}
			break;
		case R.id.btn_luu_buoc:
			isProccess = true;
			progressDialog = ProgressDialog.show(BuocThucHienActivity.this, "", "Đang lưu các bước thực hiện...");
			mHandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					if (null != progressDialog && progressDialog.isShowing())
						progressDialog.dismiss();
				}
			}, 90000);
			// goi ham luu
			
			mHandler.removeCallbacks(r);
			mHandler.post(r);
			
			break;
			
		/*case R.id.btn_thembuoc:
			addBuoclam();
			break;*/
		case R.id.btn_them:
			chitietBuoc();
			break;
		default:
			break;
		}
	}
	
	void chitietBuoc() {
		Intent t = new Intent(this, TungbuocthuchienActivity.class);
		startActivity(t);
		overridePendingTransition(R.anim.open_next, R.anim.close_main);
	}
	
	public JSONArray createDataStep(){
		step = new JSONArray();
		if (objSteps.size() == 0) {
			
		} else {
			for (int i = 0; i < objSteps.size(); i++) {
				objSteps.get(i).setStep(i+1);
				step.put(objSteps.get(i).getJsonObject());
			}
		}
		
		return step;
	}
	
	
	
	
	@Override
	protected void onResume() {
		super.onResume();
		stepCount = objSteps.size();
		createDataStep();
//		adapter.notifyDataSetChanged();
		adapter.setDataChange(objSteps);
		Log.i("DATA", "JSONARRAY: "+step);
	}

	ArrayList<ObjCachlam> fixData() {
		/*objCachlams.add(new ObjCachlam("hahahahahahahahah", "http://goo.gl/2Vooz7",1));
		objCachlams.add(new ObjCachlam("hohohohohohohohoho", "http://goo.gl/LjAa10", 2));
		objCachlams.add(new ObjCachlam("asdasdasdadadasdad", "http://goo.gl/6Ltckh", 3));
		objCachlams.add(new ObjCachlam("adasdadadadadadada", "http://goo.gl/FR8sKS", 4));*/
		return objCachlams;
	}
	

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		GridView gv = (GridView)parent;
		
	}
	
	void closeActivity(){
		finish();
		overridePendingTransition(R.anim.open_main, R.anim.close_next);
		stepCount = 0;
	}


	@Override
	public void onBackPressed() {
		if (isProccess == true) {
			showDialogProcess();
		} else {
			if(objSteps.size() == 0) {
				closeActivity();
				objSteps.clear();
			} else {
				if (isPosted == true) {
					closeActivity();
					objSteps.clear();
				} else {
					showDialogCanhbaochuapost();
				}
				
			}
		}
	}
	
	// luu thu tu cac buoc cong thuc
	void saveStepCT() {
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				super.onFailure(error);
				progressDialog.dismiss();
				isProccess = false;
				Toast.makeText(BuocThucHienActivity.this, "Cập nhật thất bại.", Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onSuccess(JSONObject re) {
				progressDialog.dismiss();
				isProccess = false;
				try {
					int status = re.getInt("status");
					switch (status) {
					case 200:
						isPosted = true;
						mHandler.postDelayed(rThoat, 200);
						Toast.makeText(BuocThucHienActivity.this, "Cập nhật thành công.", Toast.LENGTH_SHORT).show();
						break;
						
					case 400:
						Toast.makeText(BuocThucHienActivity.this, "Cập nhật thất bại.", Toast.LENGTH_SHORT).show();
						break;
					case 404:
						Toast.makeText(BuocThucHienActivity.this, "Cập nhật thất bại.", Toast.LENGTH_SHORT).show();
						break;
					}
				} catch (JSONException e) {
					Toast.makeText(BuocThucHienActivity.this, "Cập nhật thất bại.", Toast.LENGTH_SHORT).show();
					e.printStackTrace();
				}
			}
			
		});
		httpClientHelper.saveStepCT(preferenceHelper.getID(), preferenceHelper.getRecipeId(), step);
	}
	
	// show dialog dang thuc hien 1 hanh dong noa do
		public void showDialogProcess() {
			dArlert = new Dialog(BuocThucHienActivity.this,
					R.style.DialogSlideAnimLeft);
			dArlert.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dArlert.setContentView(R.layout.dialog_thoat_process);

			// khai bao cac thanh phan
			TextView txtArlert = (TextView) dArlert
					.findViewById(R.id.str_canhbao_thoat);
			Button btnThoat = (Button) dArlert.findViewById(R.id.btn_thoat);
			Button btnKoThoat = (Button) dArlert.findViewById(R.id.btn_ko_thoat);

			btnThoat.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					dArlert.dismiss();
					objSteps.clear();
					mHandler.removeCallbacks(r);
					mHandler.removeCallbacks(rThoat);
					mHandler.postDelayed(rThoat, 200);
				}
			});

			btnKoThoat.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					dArlert.dismiss();
				}
			});

			dArlert.setCanceledOnTouchOutside(true);
			dArlert.show();
			dArlert.getWindow().setBackgroundDrawable(new ColorDrawable(0));
			dArlert.getWindow().setGravity(Gravity.CENTER);
		}

		void showDialogCanhbaochuapost() {
			dChuapost = new Dialog(BuocThucHienActivity.this,
					R.style.DialogSlideAnimLeft);
			dChuapost.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dChuapost.setContentView(R.layout.dialog_thoat_process);

			// khai bao cac thanh phan
			TextView txtArlert = (TextView) dChuapost
					.findViewById(R.id.str_canhbao_thoat);
			Button btnThoat = (Button) dChuapost.findViewById(R.id.btn_thoat);
			Button btnKoThoat = (Button) dChuapost.findViewById(R.id.btn_ko_thoat);

			txtArlert
					.setText("Bạn chưa cập nhật các bước thực hiện. Bạn có muốn bỏ qua cập nhật và thoát?");
			btnThoat.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					dChuapost.dismiss();
					objSteps.clear();
					mHandler.postDelayed(rThoat, 200);
				}
			});

			btnKoThoat.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					dChuapost.dismiss();
				}
			});

			dChuapost.setCanceledOnTouchOutside(true);
			dChuapost.show();
			dChuapost.getWindow().setBackgroundDrawable(new ColorDrawable(0));
			dChuapost.getWindow().setGravity(Gravity.CENTER);
		}

}
